import 'package:dance_todo/db/bean_record.dart';
import 'package:dance_todo/main.dart';
import 'package:dance_todo/pages/BarChartSample1.dart';
import 'package:dance_todo/pages/chart_test.dart';
import 'package:dance_todo/pages/controller_trophy.dart';
import 'package:dance_todo/pages/page_statistic.dart';
import 'package:dance_todo/res/res_colors.dart';
import 'package:dance_todo/utils/utils_calender.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:lottie/lottie.dart';
import 'package:table_calendar/table_calendar.dart';

class TrophyPage extends StatefulWidget {
  @override
  _TrophyPageState createState() => _TrophyPageState();
}

class _TrophyPageState extends State<TrophyPage> {
  late final ValueNotifier<List<Record>> _selectedRecords;
  CalendarFormat _calendarFormat = CalendarFormat.month;
  RangeSelectionMode _rangeSelectionMode = RangeSelectionMode
      .toggledOff; // Can be toggled on/off by longpressing a date
  DateTime _focusedDay = DateTime.now();
  DateTime? _selectedDay;
  DateTime? _rangeStart;
  DateTime? _rangeEnd;

  @override
  void initState() {
    super.initState();
    _selectedDay = _focusedDay;
    _selectedRecords = ValueNotifier(_getEventsForDay(_selectedDay!));
  }

  @override
  void dispose() {
    _selectedRecords.dispose();
    super.dispose();
  }

  //notice 获取每一天对应的记录
  List<Record> _getEventsForDay(DateTime day) {
    return Record.queryRecords(recordBox, day);
  }

  //notice 组装全部范围内的记录
  List<Record> _getEventsForRange(DateTime start, DateTime end) {
    // Implementation example
    final days = daysInRange(start, end);
    return [
      for (final d in days) ..._getEventsForDay(d),
    ];
  }

  void _onDaySelected(DateTime selectedDay, DateTime focusedDay) {
    if (!isSameDay(_selectedDay, selectedDay)) {
      setState(() {
        _selectedDay = selectedDay;
        _focusedDay = focusedDay;
        _rangeStart = null; // Important to clean those
        _rangeEnd = null;
        _rangeSelectionMode = RangeSelectionMode.toggledOff;
      });

      _selectedRecords.value = _getEventsForDay(selectedDay);
    }
  }

  void _onRangeSelected(DateTime? start, DateTime? end, DateTime focusedDay) {
    setState(() {
      _selectedDay = null;
      _focusedDay = focusedDay;
      _rangeStart = start;
      _rangeEnd = end;
      _rangeSelectionMode = RangeSelectionMode.toggledOn;
    });

    // `start` or `end` could be null
    if (start != null && end != null) {
      _selectedRecords.value = _getEventsForRange(start, end);
    } else if (start != null) {
      _selectedRecords.value = _getEventsForDay(start);
    } else if (end != null) {
      _selectedRecords.value = _getEventsForDay(end);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.black87,
      child: SafeArea(
        child: Container(
          child: Column(
            children: [
              Container(
                child: const Text(
                  '统计',
                  style: TextStyle(
                    color: ColorActiveYellow,
                    fontSize: 70.0,
                  ),
                ),
              ),
              TableCalendar<Record>(
                firstDay: kFirstDay,
                lastDay: kLastDay,
                focusedDay: _focusedDay,
                selectedDayPredicate: (day) => isSameDay(_selectedDay, day),
                rangeStartDay: _rangeStart,
                rangeEndDay: _rangeEnd,
                calendarFormat: _calendarFormat,
                rangeSelectionMode: _rangeSelectionMode,
                eventLoader: _getEventsForDay,
                startingDayOfWeek: StartingDayOfWeek.monday,
                headerStyle: const HeaderStyle(
                  leftChevronIcon: Icon(
                    Icons.keyboard_arrow_left,
                    color: Colors.white,
                  ),
                  rightChevronIcon: Icon(
                    Icons.keyboard_arrow_right,
                    color: Colors.white,
                  ),
                  titleTextStyle: TextStyle(
                    color: ColorTitle,
                  ),
                  formatButtonTextStyle: TextStyle(
                    color: Colors.white,
                  ),
                  formatButtonDecoration: BoxDecoration(
                    color: ColorActiveRed,
                    border: Border.fromBorderSide(BorderSide()),
                    borderRadius: BorderRadius.all(Radius.circular(12.0)),
                  ),
                ),
                //工作日假期文字样式
                daysOfWeekStyle: const DaysOfWeekStyle(
                  weekdayStyle: TextStyle(color: Colors.white54),
                  weekendStyle: TextStyle(color: Colors.lightGreen),
                ),
                //日期样式
                calendarStyle: const CalendarStyle(
                  // Use `CalendarStyle` to customize the UI
                  markerDecoration: BoxDecoration(
                    color: Colors.pinkAccent,
                    shape: BoxShape.circle,
                  ),
                  outsideDaysVisible: false,
                  defaultTextStyle: TextStyle(
                    color: Colors.white,
                  ),
                  selectedTextStyle: TextStyle(
                    color: Colors.pinkAccent,
                  ),
                  // disabledTextStyle: TextStyle(
                  //   color: Colors.transparent,
                  // ),
                ),
                onDaySelected: _onDaySelected,
                onRangeSelected: _onRangeSelected,
                onFormatChanged: (format) {
                  if (_calendarFormat != format) {
                    setState(() {
                      _calendarFormat = format;
                    });
                  }
                },
                onPageChanged: (focusedDay) {
                  _focusedDay = focusedDay;
                },
              ),
              const SizedBox(height: 8.0),
              Expanded(
                child: buildRecordsGridInDay(),
              ),
              const SizedBox(height: 8.0),
              buildMenuRow(),
              SizedBox(height: 20.0),
            ],
          ),
        ),
      ),
    );
  }

  ValueListenableBuilder<List<Record>> buildRecordsGridInDay() {
    return ValueListenableBuilder<List<Record>>(
      valueListenable: _selectedRecords,
      builder: (context, value, _) {
        return GridView.count(
          crossAxisCount: 4,
          children: value.map((record) {
            return buildRecordItem(record);
          }).toList(),
        );
      },
    );
  }

  Container buildRecordItem(Record record) {
    return Container(
      margin: const EdgeInsets.all(3.0),
      decoration: BoxDecoration(
        border: Border.all(
          color: Colors.white,
        ),
        borderRadius: BorderRadius.circular(5.0),
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Container(
            child: Text(
              '${record.name}',
              style: const TextStyle(
                color: ColorActiveRed,
                fontSize: 20.0,
              ),
            ),
          ),
          Container(
            child: Text(
              '进度： ${record.doneCount}/${record.totalCount}',
              style: const TextStyle(
                color: Colors.white70,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget buildMenuRow() {
    return Container(
      child: Row(
        children: [
          GestureDetector(
            onTap: () {
              // Get.to(()=> StatisticPage());
              Get.to(()=> PieChartSample2());
            },
            child: Container(
              width: 120.0,
              height: 100.0,
              decoration: BoxDecoration(
                color: Colors.grey.withAlpha(50),
                borderRadius: const BorderRadius.only(
                  topRight: Radius.circular(100.0),
                  bottomRight: Radius.circular(100.0),
                ),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: const [
                  Text(
                    '总计',
                    style: TextStyle(
                      color: ColorActiveRed,
                      fontSize: 40.0,
                    ),
                  ),
                ],
              ),
            ),
          ),
          Expanded(child: Container()),
          GestureDetector(
            onTap: () {
              Get.back();
            },
            child: Container(
              width: 120.0,
              height: 100.0,
              decoration: BoxDecoration(
                color: Colors.grey.withAlpha(50),
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(100.0),
                  bottomLeft: Radius.circular(100.0),
                ),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    '打卡',
                    style: TextStyle(
                      color: ColorActiveRed,
                      fontSize: 40.0,
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}
